package handler

import (
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"net/http"
	"pro/global"
	"pro/internal/models"
	"pro/internal/params"
	"pro/pkg/baidu_review"
	"pro/pkg/rabbitmq"
)

type CreateHandler struct {
	review *baidu_review.Review
	rabbit *rabbitmq.RabbitMQ
}

func NewCHandler() *VideoHandler {
	rmq := rabbitmq.NewRabbitMQSimple("review_log")
	return &VideoHandler{
		review: baidu_review.NewReview(),
		rabbit: rmq,
	}
}

func CreateComments(c *gin.Context) {
	var err error
	var cl models.CommentLog
	var req params.CreateCommentsReq
	var v models.Videos

	if err = c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	cl.UserId = req.UserId
	cl.VideoId = req.VideoId
	cl.Comment = req.Comment
	if err = cl.CreateCl(); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 400,
		})
		return
	}

	if err = global.DB.Model(&v).Where("id=?", req.VideoId).
		UpdateColumn("hot", gorm.Expr("hot + ?", 1)).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code":    400,
			"message": "热度增加失败",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "评论创建成功",
		"data":    cl,
	})
}

func CreateLikesLog(c *gin.Context) {
	var err error
	var ll models.LikesLog
	var req params.CreateLikesReq
	var v models.Videos

	if err = c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	if err = ll.GetLlById(req.UserId, req.VideoId); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"message": "点赞记录获取失败"})
		return
	}
	if ll.ID != 0 {
		c.JSON(http.StatusInternalServerError, gin.H{"message": "不可重复点赞！"})
		return
	}

	ll.UserId = req.UserId
	ll.VideoId = req.VideoId
	if err = ll.CreateLl(); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 400,
		})
		return
	}

	if err = global.DB.Model(&v).Where("id=?", req.VideoId).
		UpdateColumn("hot", gorm.Expr("hot + ?", 1)).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code":    400,
			"message": "热度增加失败",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "点赞记录创建成功",
		"data":    ll,
	})
}

func DelLikesLog(c *gin.Context) {
	var err error
	var ll models.LikesLog
	var req params.DelLikesReq

	if err = c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	if err = ll.DelLL(int64(req.UserId), int64(req.VideoId)); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 400,
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "取消点赞成功",
	})
}
